/**
 * Copyright By Grandsoft Company Limited.  
 * 2013-6-13 上午11:30:05
 */
package com.glodon.ggzy.user.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.glodon.ggzy.core.utils.Constants;
import com.glodon.ggzy.core.utils.CustomizedPropertyPlaceholderConfigurer;
import com.glodon.ggzy.core.utils.SSOUtils;
import com.glodon.ggzy.entity.ZhUser;
import com.glodon.ggzy.sso.utils.Crypt;
import com.glodon.ggzy.sso.utils.CryptString;
import com.glodon.ggzy.sso.utils.TimeUtil;
import com.glodon.ggzy.user.service.ISsoService;
import com.glodon.ggzy.webservice.Unit;

/**
 * 
 * SSO 控制类
 * @author sunpf
 * @date 2013-6-12
 *
 */
@Controller
public class SsoController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ISsoService ssoService;

	/**
	 * 建设工程
	 * @param model
	 * @return
	 */
	@RequestMapping("/role_reg_save")
	public ModelAndView saveRole(Model model, String userName, String role) {
		ZhUser user = ssoService.getUser(userName);
		if (null != user) {
			role = ssoService.getRolesByUserId(user.getId());
		} else {
			ssoService.saveUserRole(userName, role);
		}
		return new ModelAndView("redirect:index.do?userName=" + userName + "&role=" + role);
	}

	/**
	 * 注册页面
	 * @param model
	 * @param userName
	 * @return
	 */
	@RequestMapping("/role_reg")
	public String redirectRoleReg(Model model, HttpServletRequest request, HttpServletResponse response) {

		Unit user = (Unit) request.getSession().getAttribute("user_session_key");

		//如果用户为空，说明：需要重定向页面 http://19.48.228.119:9701/ZhuaPortal/TokenAuth?TokenAuthRequest=xxx		
		if (user == null) {
			String passportLoginResponse = request.getParameter(Constants.TokenAuthResponse);
			if (StringUtils.isEmpty(passportLoginResponse)) {
				try {
					String returnURL = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.REDIRECT_ROLE_REG);
					String srcSsDeviceNo = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.CLIENT_ID);
					String key = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.KEY);
					String destValue = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.SYSTEM_XIANGLIANG);
					String time = TimeUtil.getNowTime();
					String display = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.REQUEST_Display);
					String digestString = srcSsDeviceNo + time + returnURL + display;
					String digest = CryptString.buildDigest(digestString);
					String srcString = time + "$" + returnURL + "$" + display + "$" + digest;
					String tokenAuthRequest = Crypt.urlEncode(srcSsDeviceNo + "$" + CryptString.bulidEncrypyString(destValue, key, srcString));

					response.sendRedirect(CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.RedirectTokenAuth) + "?TokenAuthRequest=" + tokenAuthRequest);
					//					return "/index";
				} catch (Exception e) {
					e.printStackTrace();
					return "redirect:/index.do";
				}
			} else {
				Unit tempuser = null;
				try {
					tempuser = SSOUtils.getUser(passportLoginResponse);
				} catch (Exception e) {
					request.setAttribute("error", "登陆失败");
					e.printStackTrace();
					return "/index";
				}
				HttpSession session = request.getSession();

				if (tempuser != null)
					session.setAttribute(Constants.user_session_key, tempuser); //放入局部token

				if (tempuser == null) {
					return "redirect:/index.do";
				}
			}
		}
		Unit user2 = (Unit) request.getSession().getAttribute(Constants.user_session_key);
		if (user2 != null) {
			//判断如果此企业已经注册过，跳转到首页
			ZhUser zhUser = ssoService.getUser(user2.getOrganizationCode());
			if (null != zhUser) {
				return "redirect:/index.do";
			}
			model.addAttribute("userName", user2.getOrganizationCode());
		}

		return "/role_reg";
	}

	/**
	 * 首页面
	 * @param model
	 * @param userName
	 * @param role
	 * @return
	 */
	@RequestMapping("/index")
	public String redirectIndex(Model model, String userName, String role, HttpServletRequest request) {
		//从其他系统链接过来参数名字是不是 TokenAuthRequest

		//		参数名称	数据类型	长度	频次	说明
		//		Result	Integer	2	1	0：成功1：失败
		//		ClientId	String	16	1	返回方系统标识【统一认证平台】
		//		Ticket	String	64	0-1	返回给应用系统的Ticket信息； 若认证失败，则不返回该值。
		//		TimeStamp	String	19	1	时间戳yyyy-MM-dd HH:mm:ss，其中HH取值为00-23，时区为东八区

		String passportLoginResponse = request.getParameter(Constants.TokenAuthResponse);
		/***************三种方式登陆我们系统*****************/

		/***************1.直接从网址到达我们系统*****************/
		//直接返回页面
		HttpSession session = request.getSession();
		Unit attribute = (Unit) session.getAttribute(Constants.user_session_key);

		if (attribute != null) {
			ZhUser zhUser = ssoService.getUser(attribute.getOrganizationCode());
			String rolesByUser = ssoService.getRolesByUserId(zhUser.getId());
			model.addAttribute("role", rolesByUser);
			model.addAttribute("userName", zhUser.getUserName());
			return "/index";
		} else {
			if (StringUtils.isEmpty(passportLoginResponse)) {
				return "/index";
			} else {
				/***************2.从其他系统到达我们系统*****************/
				//解析此paremeter
				Unit user = null;
				try {
					user = SSOUtils.getUser(passportLoginResponse);
				} catch (Exception e) {
					request.setAttribute("error", "登陆失败");
					// TODO Auto-generated catch block
					e.printStackTrace();
					return "/index";
				}
				if (user != null) {
					ZhUser zhUser = ssoService.getUser(user.getOrganizationCode());
					String rolesByUser = ssoService.getRolesByUserId(zhUser.getId());
					model.addAttribute("role", rolesByUser);
					model.addAttribute("userName", userName);

					session.setAttribute(Constants.user_session_key, user); //放入局部token
				}
				
				
				if(user == null){
					request.setAttribute("error", "个人注册用户不能注册角色或者单点登陆失败，请联系管理员");
					return "/index";
				}
			}
		}

		return "/index";
	}

	/**
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
		return "/index";
	}
	
	@RequestMapping("/local_logout")
	public String localLogout(Model model, HttpServletRequest request, HttpServletResponse response) {
		String passportLogoutURL = getPassportLogoutURL(CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.LogoutResponseUrl));
		try {
			response.sendRedirect(passportLogoutURL);
		} catch (IOException e) {
			request.setAttribute("error", "验证签名失败！");
			return "/index";
		}
		
		return "/index";
	}
	
	
	
	/**
	 * 全局注销方法：从别的系统中退出时，把本系统也注销掉
	 * 此方法不能修改：提供给统一验证平台的注销方法
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout_global")
	public String logout_global(Model model, HttpServletRequest request, HttpServletResponse response) {
		try {
			String logoutResponseValue = request.getParameter(Constants.LogoutResponse);
			String logoutResponseseValueArray[] = logoutResponseValue.split("\\$");
	   		String uaDeviceNo = logoutResponseseValueArray[0];
	        String destValue = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.SYSTEM_XIANGLIANG);
	           //业务系统的密匙，在Config中的key
	        String key = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.KEY);
	   		String decryptString = CryptString.getDecryptString(logoutResponseseValueArray[1],destValue,key);//解密请求参数
	   		String[] decryptStrings = decryptString.split("\\$");
	   		String digestSrcString = "";
	   		//生成要加密的 digest 字符串
	   		digestSrcString += decryptStrings[0];
	   		digestSrcString += uaDeviceNo;
	   		digestSrcString += decryptStrings[1];
	   		boolean checkdigest = CryptString.checkDigest(decryptStrings[decryptStrings.length - 1], digestSrcString);//验证签名
	   		if (!checkdigest) {
		    		request.setAttribute("error", "验证签名失败！");
	   		}
	   		String resultCode = decryptStrings[0];
	   		
	   		if("0".equals(resultCode)) {
	   		//注销成功
	   			HttpSession session = request.getSession();
	   			session.setAttribute(Constants.user_session_key, null);
	   			System.err.println("注销成功");
	   		} else {
	   		//注销失败
	   			request.setAttribute("error", "系统出现了错误,没有正常退出,请联系统一交换平台");
	   		}	
		} catch (Exception e) {
			return "/index";
		}
		
		return "/index";
	}
	
	
	   //加密重定向令牌注销请求参数
    private String getPassportLogoutURL(String returnURL) {
        try {
            String destValue = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.SYSTEM_XIANGLIANG);
            //业务系统的密匙，在Config中的key
            String key = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.KEY);
            String time = TimeUtil.getNowTime();
            String clientId = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.CLIENT_ID);
			String digestString = clientId + time + returnURL;
            String digest = CryptString.buildDigest(digestString);
            String srcString = time + "$" + returnURL + "$" + digest;
            String logoutrequestValue = Crypt.urlEncode(clientId + "$" + CryptString.bulidEncrypyString(destValue, key, srcString));
            String logoutRequestUrl = CustomizedPropertyPlaceholderConfigurer.getProperty(Constants.LogoutRequestUrl);
            String url = logoutRequestUrl +"="+ logoutrequestValue;
            return url;
        } catch (Exception ex) {
        	ex.printStackTrace();
            return null;
        }
    }

	public String isRegistered(Model model) {
		return null;
	}

}
